﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Syndication;
using System.Xml.Linq;
using System.Xml;

namespace ajayumi.develop.win32.GRssReader.Service.Base
{
    public abstract class XElementItemBase : SyndicationItem
    {
        /// <summary>
        /// Initialize the item.
        /// </summary>
        /// <param name="item"></param>
        public XElementItemBase(XElement item)
        {
            if (item != null)
            {
                LoadItem(item);
            }
        }

        /// <summary>
        /// Load the item (to be implemented by inheriting classes).
        /// </summary>
        /// <param name="item"></param>
        protected abstract void LoadItem(XElement item);

        /// <summary>
        /// Get a list of descendants.
        /// </summary>
        /// <param name="item"></param>
        /// <param name="descendant"></param>
        /// <param name="attribute"></param>
        /// <param name="attributeValue"></param>
        /// <returns></returns>
        protected IEnumerable<XElement> GetDescendants(XElement item, string descendant, string attribute, string attributeValue)
        {
            return item.Descendants(descendant).Where(o => o.Attribute(attribute) != null && o.Attribute(attribute).Value == attributeValue);
        }

        /// <summary>
        /// Get a descendant.
        /// </summary>
        /// <param name="item"></param>
        /// <param name="descendant"></param>
        /// <param name="attribute"></param>
        /// <param name="attributeValue"></param>
        /// <returns></returns>
        protected XElement GetDescendant(XElement item, string descendant, string attribute, string attributeValue)
        {
            IEnumerable<XElement> enumerable = GetDescendants(item, descendant, attribute, attributeValue);
            if (enumerable.Count() > 0)
            { return enumerable.First(); }
            return null;
        }

        /// <summary>
        /// Get the value of a descendant.
        /// </summary>
        /// <param name="item"></param>
        /// <param name="descendant"></param>
        /// <param name="attribute"></param>
        /// <param name="attributeValue"></param>
        /// <returns></returns>
        protected string GetDescendantValue(XElement item, string descendant, string attribute, string attributeValue)
        {
            var desc = GetDescendant(item, descendant, attribute, attributeValue);
            if (desc != null)
                return desc.Value;
            else
                return "";
        }
    }
}
